package com.gy.paidao.main;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.PopupWindow;

import com.google.gson.reflect.TypeToken;
import com.gy.paidao.MainActivity;
import com.gy.paidao.MyApplication;
import com.gy.paidao.R;
import com.gy.paidao.bean.BaseBean;
import com.gy.paidao.main.adapter.MainListAdapter;
import com.gy.paidao.main.bean.ActivityBean;
import com.gy.paidao.util.AnimUtil;
import com.gy.paidao.util.BuileGestureExt;
import com.gy.paidao.util.ListViewItemListener;
import com.gy.paidao.util.LogUtil;
import com.gy.paidao.util.SPHelper;
import com.gy.paidao.util.Urls;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.jky.struct2.http.core.AjaxParams;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * @author GY
 * @date 16/3/2
 * @Description:泡泡列表页
 */
public class MainListFragment extends BaseFragment implements
        PullToRefreshBase.OnRefreshListener2,ListViewItemListener,AdapterView.OnItemClickListener {

    private static int pageSize = 10;
    private View mRoot;
    private PullToRefreshListView listView;
    private MainListAdapter mainListAdapter;
    private GestureDetector gestureDetector;
    private List<ActivityBean> datas,requestList;
    private String userLoginID;
    private String search;
    private int lastItemId = -1;

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if("new_bubble".equals(intent.getAction())){
                lastItemId = -1;
                datas.clear();
                dorequestActivity();
            } else if("search_activity".equals(intent.getAction())){
                search = intent.getStringExtra("search");
                datas.clear();
                showLoadDialog(1);
                dorequestActivity();
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if(mRoot == null){
            mRoot = inflater.inflate(R.layout.fg_main_list,null);
            init();
            initView();
            showLoadDialog();
            dorequestActivity();
        }
        ViewGroup parent = (ViewGroup) mRoot.getParent();
        if (parent != null) {
            parent.removeView(mRoot);
        }
        return mRoot;
    }

    @Override
    protected void init() {
        super.init();
        userLoginID = SPHelper.getInstance(getActivity()).getStringData("userLoginID",null);
        datas = new ArrayList<ActivityBean>();
        requestList = new ArrayList<ActivityBean>();
        mainListAdapter = new MainListAdapter(mContext,datas);
        mainListAdapter.setListener(this);

        IntentFilter filter = new IntentFilter();
        filter.addAction("new_bubble");
        filter.addAction("search_activity");
        mContext.registerReceiver(receiver,filter);

        gestureDetector = new BuileGestureExt(mContext,new BuileGestureExt.OnGestureResult() {
            @Override
            public void onGestureResult(int direction) {
                if(getResources().getString(R.string.tab_home).equals(((MainActivity)getActivity()).mTab)){
                    if(direction == 2){//left
                        ((MainActivity)getActivity()).changeByMainList(2,2);
                    } else if(direction == 3){//right
                        ((MainActivity)getActivity()).changeByMainList(0,0);
                    }
                }
            }
        }
        ).Buile();

        ((MainActivity)getActivity()).registerMyTouchListener(new MainActivity.MyTouchListener() {
            @Override
            public void onTouchEvent(MotionEvent event) {
                gestureDetector.onTouchEvent(event);
            }
        });
    }

    @Override
    protected void initView() {
        super.initView();
        listView = (PullToRefreshListView) mRoot.findViewById(R.id.fg_main_list);
        listView.setOnRefreshListener(this);
        listView.setAdapter(mainListAdapter);
        listView.setMode(PullToRefreshBase.Mode.BOTH);
        listView.setOnItemClickListener(this);
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        lastItemId = -1;
        dorequestActivity();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        if(requestList != null && requestList.size() == pageSize){
            dorequestActivity();
        } else {
            showToast("已全部加载");
            handler.sendEmptyMessageDelayed(0,500);
        }
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            listView.onRefreshComplete();
        }
    };

    /** 请求列表*/
    private void dorequestActivity(){
        params = new AjaxParams();
//        params.put("latitude", MyApplication.CURRENT_Y+"");
//        params.put("longitude",MyApplication.CURRENT_X+"");

        if(!TextUtils.isEmpty(search)){
            params.put("search",search);
        }
        params.put("lastItemId",lastItemId+"");
        httpRequest.addHeader("Cookie", "userLoginID=" + userLoginID);
        httpRequest.get(Urls.url_activity,params,callBack,0);
    }

    /** 加热接口*/
    private void dorequestFire(String uid){
        params = new AjaxParams();
        params.put("activityId",uid+"");
        httpRequest.addHeader("Cookie", "userLoginID=" + userLoginID);
        httpRequest.post(Urls.url_fire,params,callBack,1);
    }

    /** 删除接口*/
    private void dorequestDelete(String uid){
        showLoadDialog();
        params = new AjaxParams();
        params.put("activityId",uid+"");
        httpRequest.addHeader("Cookie", "userLoginID=" + userLoginID);
        httpRequest.post(Urls.url_delete_activity,params,callBack,2);
    }

    @Override
    protected void handlerBean(int requestCode, BaseBean baseBean) {
        super.handlerBean(requestCode, baseBean);
        if(baseBean.success){
            String data = String.valueOf(baseBean.data);
            switch (requestCode){
                case 0://请求列表
                    handler.sendEmptyMessageDelayed(0, 500);
                    if(lastItemId == -1){
                        datas.clear();
                    }
                    if(!TextUtils.isEmpty(data)){
                        try {
                            JSONObject obj = new JSONObject(data);
                            String resule = obj.optString("datas");
                            if(!TextUtils.isEmpty(resule) && !"[]".equals(resule)){
                                Type type = new TypeToken<List<ActivityBean>>(){}.getType();
                                requestList = gson.fromJson(resule,type);
                                datas.addAll(requestList);
                                mainListAdapter.notifyDataSetChanged();
                                lastItemId = requestList.get(requestList.size() - 1).id;
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                case 1://加热
                    try {
                        JSONObject obj = new JSONObject(data);
                        int activityId = obj.optInt("activityId");
                        int heatValue = obj.optInt("heatValue");
                        for (int i =0; i < datas.size(); i++){
                            if(datas.get(i).id == activityId){
                                ActivityBean bean = datas.get(i);
                                bean.heatValue = heatValue;
                                datas.set(i,bean);
                                break;
                            }
                        }
                        mainListAdapter.notifyDataSetChanged();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case 2:
                    try {
                        JSONObject obj = new JSONObject(data);
                        int activityId = obj.optInt("activityId");
                        for (int i =0; i < datas.size(); i++){
                            if(datas.get(i).id == activityId){
                                datas.remove(i);
                                break;
                            }
                        }
                        mainListAdapter.notifyDataSetChanged();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
            }
        } else {
            if(!TextUtils.isEmpty(baseBean.errMsg)){
                showToast(baseBean.errMsg);
            }
        }
    }

    @Override
    public void handleNetErr(int requestCode, int errorCode) {
        super.handleNetErr(requestCode, errorCode);
        handler.sendEmptyMessageDelayed(0, 500);
    }

    @Override
    public void doPassActionListener(Object obj, int org1, int org2, String str) {
        switch (org1){
            case 1://热
                dorequestFire(datas.get(org2).id+"");
                break;
            case 2://评论
                Intent intent = new Intent(mContext,BabbleDetailActivity.class);
                Bundle bundle = new Bundle();
                bundle.putInt("intoDetail",1);
                bundle.putSerializable("activity",datas.get(org2));
                intent.putExtras(bundle);
                startActivity(intent);
                AnimUtil.pushLeftInAndOut(getActivity());
                break;
            case 3://删除
                dorequestDelete(datas.get(org2).id+"");
                break;
        }
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(mContext,BabbleDetailActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("activity",datas.get(position-1));
        intent.putExtras(bundle);
        startActivity(intent);
        AnimUtil.pushLeftInAndOut(getActivity());
    }

}
